<?php

Yii::import('lib.ext.pay.tenpay.PayRequestHandler');
Yii::import('lib.ext.pay.tenpay.PayResponseHandler');

class Tenpay extends CComponent{

	public $paymentId;
	public $paymentKey;
	public $paymentAccount;
	public $returnUrl;
	protected $_tid;
	protected $_price = 0;
	protected $_notify = array();
	
	public function getOrderNo(){
		$curDateTime = date("YmdHis");
		$randNum = rand(1000, 9999);
		return $curDateTime . $randNum;
	}
	
	public function getTid(){
		$bargainor_id = $this->paymentId;
		$strDate = date("Ymd");
		$strTime = date("His");
		$randNum = rand(1000, 9999);
		$strReq = $strTime . $randNum;
		return empty($this->_tid) ? $this->_tid = $bargainor_id . $strDate . $strReq : $this->_tid;
	}
	
	public function pay($transaction_id,$product_name,$order_price){
		//转换为gbk编码，财付通默认gbk
		$product_name =	iconv('UTF-8', 'GBK', $product_name);
		$order_no = $this->getOrderNo();
		$bargainor_id = $this->paymentId;
		$key = $this->paymentKey;
		$return_url = $this->returnUrl;
		$sp_billno = $order_no;
		$total_fee = $this->_price = $order_price*100;
		$desc = $product_name;
		$reqHandler = new PayRequestHandler();
		$reqHandler->init();
		$reqHandler->setKey($key);
		$reqHandler->setParameter("bargainor_id", $bargainor_id);			//商户号
		$reqHandler->setParameter("sp_billno", $sp_billno);					//商户订单号
		$reqHandler->setParameter("transaction_id", $transaction_id);		//财付通交易单号
		$reqHandler->setParameter("total_fee", $total_fee);					//商品总金额,以分为单位
		$reqHandler->setParameter("return_url", $return_url);				//返回处理地址
		$reqHandler->setParameter("desc", $desc);	//商品名称  
		$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);
		$reqUrl = $reqHandler->getRequestURL();
		$reqHandler->doSend();
	}
	
	public function getPrice(){
		return $this->_price;
	}
	
	public function getNotify(){
		$resHandler = new PayResponseHandler();
		$resHandler->setKey($this->paymentKey);
		$result['code'] = false;
		if(empty($this->_notify) && $resHandler->isTenpaySign()) {
			$pay_result = $resHandler->getParameter("pay_result");
			if( "0" == $pay_result ){
				//交易单号
				$result['tid'] = $this->_tid = $resHandler->getParameter("transaction_id");
				$result['price'] = $this->_price = $resHandler->getParameter("total_fee") / 100;
				$result['code'] = true;
			}
			$this->_notify = $result;
		}
		return $result['code'];
	}
}

?>